package com.itheima.web;

import com.itheima.bean.User;
import com.itheima.common.R;
import com.itheima.service.UserService;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;


@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping("/sms")
    public R valCode(String phone, HttpSession session) {

        String code4String = ValidateCodeUtils.generateValidateCode4String(4);

        session.setAttribute(phone, code4String);



        return R.success(code4String);

    }

    @PostMapping("/login")
    public R login(@RequestBody Map<String, String> map, HttpSession session) {
        String phone = map.get("phone");
        String code = map.get("code");

        String code2 = (String) session.getAttribute(phone);

        System.out.println("==========code2 = " + code2);
        if (code2 != null && code2.equalsIgnoreCase(code)) {

            User user = userService.findByUserPhone(phone);

            if (user == null) {
                user = new User();
                user.setName(phone);
                user.setStatus(1);
                user.setPhone(phone);

                int row = userService.add(user);
                if (row > 0) {
                    session.setAttribute("user", user);
                    return R.success("登录成功");
                }
                return R.error("登录失败");
            } else {
                session.setAttribute("user", user);
                return R.success("登录成功");
            }
        }
        return R.error("登录失败");
    }
}
